package processing_layer;

import java.util.HashSet;

import database_layer.Common;

/**
 * This class is in charge of keeping track over which users are currently
 * connected and which are not. We don't want a the same user connecting with two different
 * sessions.
 * 
 * Note that this is the only synchronized class in the implementation, since it holds
 * vital data which is shared / queried by many (potential) clients.
 * 
 * We decided to use synchronized locking instead of saving this in the DB, and allowing
 * it to adjust the locking methods because we wanted to save the DB queries.
 */
public class SessionTracker
{
	private static HashSet<String> connectedUsers = new HashSet<String>();
	
	public static int addConnectedUser(String username)
	{
		int returnValue = Common.NO_ERROR;;
		
		synchronized(connectedUsers)
		{
			if (false == connectedUsers.add(username))
			{
				/* Already exists */
				returnValue = Common.ENTRY_EXISTS;
			}
			else
			{
				returnValue = Common.NO_ERROR;
			}
		}
		return returnValue;
	}
	
	public static int removeDisconnectedUser(String username)
	{
		int returnValue = Common.NO_ERROR;;
		
		synchronized(connectedUsers)
		{
			if (false == connectedUsers.remove(username))
			{
				/* Already exists */
				returnValue = Common.ENTRY_DOESNT_EXIST;
			}
			else
			{
				returnValue = Common.NO_ERROR;
			}
		}
		return returnValue;
	}
	
	public static boolean isAlreadyConnected(String username)
	{
		boolean flag = false;
		
		synchronized(connectedUsers)
		{
			flag = connectedUsers.contains(username);
		}
		
		return flag;
	}
	
	public static void cleanEntries()
	{
		synchronized(connectedUsers)
		{
			connectedUsers.clear();
		}
	}
}
